package com.me.waterphase.listener;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.Manifold;
import com.me.waterphase.WaterEnergySource;
import com.me.waterphase.WaterPlayer;
import com.me.waterphase.WaterWorld;
import com.me.waterphase.listener.contact.EnergyContact;
import com.me.waterphase.listener.contact.ICustomContact;
import com.me.waterphase.utils.PhysicManager.CONTACT_TYPE;

public class EnergyListener {

public static void beginContact(Contact contact, boolean _isA) {
		
		if(_isA)
		{
			if(contact.getFixtureB().getUserData() != null)
				((EnergyContact)contact.getFixtureA().getUserData()).increment();
		}	
		else
		{
			if(contact.getFixtureA().getUserData() != null)
				((EnergyContact)contact.getFixtureB().getUserData()).increment();
		}
	}

	public static void endContact(Contact contact, boolean _isA) {
		
		if(_isA)
		{
			if(contact.getFixtureB().getUserData() != null)
				((EnergyContact)contact.getFixtureA().getUserData()).decrement();
		}	
		else
		{
			if(contact.getFixtureA().getUserData() != null)
				((EnergyContact)contact.getFixtureB().getUserData()).decrement();
		}
	}

	public static void preSolve(Contact contact, Manifold oldManifold, boolean _isA) {
		
		contact.setEnabled(false);
		
		//Give energy to element within the source.
		if(_isA)
		{
			if(contact.getFixtureB().getUserData() != null && ((ICustomContact)contact.getFixtureB().getUserData()).getContactType() == CONTACT_TYPE.USERDATA_PLAYER)
			{
				WaterEnergySource source = ((EnergyContact)contact.getFixtureA().getUserData()).getEnergySource();
				WaterPlayer player = WaterWorld.getInstance().getPlayer(); 
				
				if(!source.getAffectedObjects().contains(player))
				{
					source.getAffectedObjects().add(player);
					player.setTemperature(player.getTemperature()+(source.getDiffusedEnergyPerSecond()*Gdx.graphics.getDeltaTime()));
				}
			}
		}	
		else
		{
			if(contact.getFixtureA().getUserData() != null && ((ICustomContact)contact.getFixtureB().getUserData()).getContactType() == CONTACT_TYPE.USERDATA_PLAYER)
			{
				WaterEnergySource source = ((EnergyContact)contact.getFixtureB().getUserData()).getEnergySource();
				WaterPlayer player = WaterWorld.getInstance().getPlayer(); 
				
				if(!source.getAffectedObjects().contains(player))
				{
					source.getAffectedObjects().add(player);
					player.setTemperature(player.getTemperature()+(source.getDiffusedEnergyPerSecond()*Gdx.graphics.getDeltaTime()));
				}
			}
		}
	}

	public static void postSolve(Contact contact, ContactImpulse impulse, boolean _isA) {
		
	}
	
}
